// pages/home/home.js
var aliyun_api = require('../../utils/aliyun-api-gateway.js');
var util = require('../../utils/util.js');
var ble = require('../../utils/bluetooth.js');
var event = require('../../utils/event.js');
// const md5 = require('../../utils/md5.js');

const app = getApp()
// let buffer
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    ifBleConnected: [],
    hasDevice:true,
    hasLogin: true,
    netOk:true,
    date:'',
    lockList:[],
    refresh: 'refresh',
    top:290,
    top_i:290,
    refreshstate: 2,   //0:可以进入刷新状态；1:在刷新中；2:不可以进入刷新状态
    height: 0,
    startY: 0,
    scrollToTop: true,
    bOpenLock: true,
    nowTime:null,
    ifstarted: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // var windowHeight = (app.globalData.SystemInfo.windowHeight * (750 / app.globalData.SystemInfo.windowWidth))
    var query = wx.createSelectorQuery()
    query.select('.page').boundingClientRect();
    query.exec(function (res) {
      // console.log(res[0].height) 
      that.setData({
        height: (res[0].height * (750 / app.globalData.SystemInfo.windowWidth))-290
      })
    })
    
    var datetime = util.formatTime(new Date());
    var date = new Date()
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    that.setData({
      date: year + '年' + month + '月' + day + '日' + ' ' + datetime[2],
      // height: windowHeight - 420,
    })
    const value = wx.getStorageSync('accountInfo')
    if (!value) {
      that.setData({
        hasLogin: false
      })
      return
    }

    var cnt = that.data.lockList.length
    var BleConnected = []
    for (let i = 0; i < cnt; i++) {
      BleConnected[i] = false;
    }
  //  BleConnected[that.data.index] = app.globalData.BLE.connected
    that.setData({
      ifBleConnected: BleConnected
    })

    event.$on('BLE-connected-event', (sts) => {
      var cnt = that.data.lockList.length
      var BleConnected = []
      for (let i = 0; i < cnt; i++) {
        BleConnected[i] = false;
      }
      BleConnected[that.data.index] = sts
      that.setData({
        ifBleConnected: BleConnected
      })
    })

    event.$on('ready-event', (data) => {
      that.data.bOpenLock = true
    })

    event.$on('send-open-event', async function () {
      console.log('send-open-event')
      var content = []
      content[0] = 0x01
      content[1] = 0x00
      content[2] = 0x00
      var result = await ble.sendMsg(0x05, null, content, null)
      console.log('result', result)
      if (result == 5) {
        event.$fire('open-success-event')
      } else {
        event.$fire('open-fail-event')
      }
    })
    
    event.$on('open-success-event', (data) => {
      console.log('开门成功')
      wx.showToast({
        title: '开门成功',
        icon: 'success',
        duration: 1000
      })
      that.data.bOpenLock = true;
    })

    event.$on('open-fail-event', (data) => {
      console.log('开门失败')
      wx.showToast({
        title: '开门失败',
        duration: 1000,
        image: '/images/fail.png'
      })
      that.data.bOpenLock = true;
    })
    
    that.updateDeviceList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    var data = app.globalData.kvStorage;
    if ((that.data.hasDevice) && (data!='')){
      that.setData({
        lockList: data.deviceList
      });
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    event.$off('BLE-connected-event')
    event.$off('ready-event')
    event.$off('send-open-event')
    event.$off('open-success-event')
    event.$off('open-fail-event')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.updateDeviceList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  
  /**
   * 跳转锁具详情页面
   */
  openDetailPage: function (e) {
    var that = this
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        if (networkType === 'none') {
          that.setData({
            netOk: false
          });
        } else {
          var index = e.currentTarget.dataset.index
          wx.navigateTo({
            url: "../lock_detail/lock_detail?index=" + index 
          })
        }
      }
    })
  },

  /**
   * 扫描二维码
   */
  scan: function () {
    var that = this
    that.scanCode()
  },
  
  /**
   * @description: 开锁
   * @param {type} 
   * @return: 
   */
  OpenLock: function (e) {
    app.globalData.stopUpgrade = false
    var that = this
    if (!that.data.bOpenLock) {
      return
    }
    that.data.bOpenLock = false;
    app.globalData.bletype = 0;

    var index = e.currentTarget.dataset.index
    var deviceName = that.data.lockList[index].deviceName
    that.setData({
      index: index
    })

    if ((app.globalData.BLE.deviceName) && (app.globalData.BLE.deviceName != deviceName)) {
      var cnt = that.data.lockList.length
      var BleConnected = []
      for (let i = 0; i < cnt; i++) {
        BleConnected[i] = false;
      }
      that.setData({
        ifBleConnected: BleConnected
      })
    }

    app.globalData.BLE.deviceName = deviceName
    console.log('deviceName:', app.globalData.BLE.deviceName)
  //  app.globalData.BLE.deviceName = 'WW2'
    // var dn = []
    // dn[0] = 'WW'
    // dn[1] = 'WW2'
    // app.globalData.BLE.deviceName = dn[index]

    if (that.data.ifBleConnected[index]) {
      event.$fire('send-open-event')
    } else {
      ble.Search()
    }
  },

  /* 添加设备按钮 */
  addDeviceBtn: function () {
    var that = this
    that.scanCode()
  },
  /* 更新设备列表 */
  updateDeviceList:function () {
    var that = this
    const phone = wx.getStorageSync('accountInfo')
    const params = {
      url: 'https://api.link.aliyun.com/kvstore/get',
      apiVer: '1.1.0',
      param: {
        "key": phone
      }
    }
    return new Promise(function (resolve, reject){
      aliyun_api.request(params).then(function (res) {
        //  console.log(res.data)
        var data = JSON.parse(res.data)
        app.globalData.kvStorage = data
        that.setData({
          netOk: true
        });
        if (that.isArray(data.deviceList) && data.deviceList.length !== 0) {
          that.setData({
            hasDevice: true,
            lockList: data.deviceList
          });
          console.log(that.data.lockList)
        } else {
          that.setData({
            hasDevice: false
          });
        }
        // wx.stopPullDownRefresh();
        resolve();
      })
        .catch(function () {
          /** 显示刷新失败缺省页 */
          that.setData({
            netOk: false
          });
          wx.stopPullDownRefresh();
          reject();
        })
        
    })
    
  },
  /* 添加设备 */
  addDev: function (productKey, deviceName) {
    var that = this
    var obj = {
      productKey: productKey,
      deviceName: deviceName,
      deviceNick: deviceName
    }
    var data = app.globalData.kvStorage
    if (that.isArray(data.deviceList)) {
      data.deviceList.push(obj)
    }
    else {
      var array = []
      array.push(obj)
      data.deviceList = array
    }
    const phone = wx.getStorageSync('accountInfo')
    const params = {
      url: 'https://api.link.aliyun.com/kvstore/put',
      apiVer: '1.1.0',
      param: {
        "key": phone,
        "value": JSON.stringify(data)
      }
    }
    return new Promise(function (resolve, reject) {
      aliyun_api.request(params).then(function (res) {
        wx.showToast({
          title: '添加设备成功',
          icon: 'none',
          duration: 2000
        })
        resolve()
      })
      .catch(function () {
        wx.showToast({
          title: '添加设备失败',
          icon: 'none',
          duration: 2000
        })
        reject()
      })
    })
  },
  /* 解析二维码 */
  parseCode: function (code) {
    if (code.substr(0, 4) !== 'CETC') {
      return null
    }
    var info = code.substring(5)
    var data = info.split('-')
    var productKey = data[0]
    var deviceName = data[1]
    return {
      productKey: productKey,
      deviceName: deviceName
    }
  },
  /* 扫描二维码方法 */
  scanCode: function () {
    wx.scanCode({
      //  onlyFromCamera: true,
      success: (res) => {
        console.log(res.result)
        var that = this
        var obj = that.parseCode(res.result)
        if ((!obj) || (!obj.productKey || !obj.deviceName)) {
          wx.showToast({
            title: '二维码类型错误，请重新扫描',
            icon: 'none',
            duration: 2000
          })
        }
        /** 判断设备在云端是否存在 */
        const params = {
          url: 'https://api.link.aliyun.com/thing/device/info/get',
          apiVer: '1.1.2',
          param: {
            "productKey": obj.productKey,
            "deviceName": obj.deviceName
          }
        }
        aliyun_api.request(params).then(function (res) {

          /** 判断设备在KV里是否存在 */
          const phone = wx.getStorageSync('accountInfo')
          const params1 = {
            url: 'https://api.link.aliyun.com/kvstore/get',
            apiVer: '1.1.0',
            param: {
              "key": phone,
            }
          }
          aliyun_api.request(params1).then(function (res) {
            console.log(res.data)
            var data = JSON.parse(res.data)
            for (let i = 0; i < data.deviceList.length; i++){
              if (data.deviceList[i].productKey == obj.productKey){
                if (data.deviceList[i].deviceName == obj.deviceName){
                  wx.showToast({
                    title: '请勿重复添加设备',
                    icon: 'none',
                    duration: 2000
                  })
                  return
                }
              }
            }
            wx.showModal({
              title: '提示',
              content: `确定添加设备${obj.deviceName}吗？`,
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                  that.addDev(obj.productKey, obj.deviceName).then(that.updateDeviceList)
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          })
          .catch(function(res){
            wx.showToast({
              title: '云端请求失败',
              icon: 'none',
              duration: 2000
            })
          })
        })
        .catch(function(res){
          if (res.data.code === 6100) {
            wx.showToast({
              title: '设备在云端未注册',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })
  },
  isArray: function (obj) {
    return typeof obj == 'object' && obj.constructor == Array
  },
  /* 刷新 */
  query: function () {
    var that = this;
    var query = wx.createSelectorQuery()
    var top;
    query.select('.lock-view').scrollOffset();
    query.select('.lock-view').boundingClientRect();
    return new Promise(function (resolve, reject) {
      query.exec(function (res) {
        top = res[0].scrollTop
        resolve(top)
      })
    })
  },

  drawStart: function (e) {
    var that = this;
    that.data.ifstarted = false
    that.query().then(result => {
      // console.log(result)
      if (result == 0) {
        that.data.ifstarted = true
        that.data.scrollToTop = true;
        that.data.refreshstate = 0;
        var touch = e.touches[0]
        that.data.startY = touch.clientY
      }
      else {
        that.data.scrollToTop = false;
      }
    })
  },
  drawEnd: function (e) {
    var that = this;
    if (!that.data.ifstarted || !that.data.hasLogin) {
      return
    }
    // console.log("start", that.data.startY)
    // console.log("end",e.changedTouches[0].clientY)
    var disY = e.changedTouches[0].clientY - that.data.startY
    if (that.data.refreshstate == 0 && that.data.scrollToTop) {
      if (disY >= 50) {
        that.data.refreshstate = 1;
        that.setData({
          refresh: 'refresh1',
          top: 420,
        })
        that.updateDeviceList().then(result => {
          setTimeout(function(){
            that.setData({
              refresh: 'refresh',
              top: that.data.top_i,
              netOk: true,
            })
          that.data.refreshstate = 0;
          },1000)
          
        })
          .catch(function () {
            setTimeout(() => {
              that.data.refreshstate = 0;
              that.setData({
                refresh: 'refresh',
                top: that.data.top_i,
                netOk: false
              })
            }, 500);
          })
      } else {
        that.setData({
          top: that.data.top_i
        })
      }
    }
  },

  bindGetUserInfo: function (e) {
    var that = this;
    util.NetStatusOk().then(function () {
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        app.globalData.userInfo = e.detail.userInfo;
        //授权成功后，跳转进入小程序首页
        wx.reLaunch({
          url: '../authorize/authorize',
        })
      } else {
        //用户按了拒绝按钮
      }
    })
  },
})